<template>
  <div class="padding flex direction-column height-100">
    <div class="search-form">
      <el-form inline>
        <el-form-item label="报告年月份">
          <el-date-picker
            v-model="year"
            type="year"
            value-format="yyyy"
            placeholder="选择年"
            :clearable="false"
            :editable="false"
            :picker-options="pickerOptions"
          ></el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="query">
            查询
          </el-button>
        </el-form-item>
      </el-form>
    </div>
    <el-table
      v-loading="loading"
      class="table"
      :data="lists"
      height="100%"
      :header-cell-style="{
        color: 'white',
        backgroundColor: themeColor
      }"
    >
      <el-table-column
        v-for="column in columns"
        :key="column.prop"
        v-bind="column"
      >
        <template #default="{ row }">
          <template v-if="column.prop === 'name'">
            <a
              v-if="row.state === 2"
              href="javascript:void(0)"
              type="text"
              @click="download(row)"
            >
              {{ row.name }}
            </a>
            <span v-else>{{ row.name }}</span>
          </template>
          <template v-else-if="column.prop === 'state'">
            {{
              row.state === 0
                ? '未生成'
                : row.state === 1
                ? '生成中'
                : row.state === 2
                ? '已生成'
                : '生成失败'
            }}
          </template>
          <template v-else>
            {{ row[column.prop] }}
          </template>
        </template>
      </el-table-column>

      <el-table-column label="操作" prop="operate">
        <template #default="{ row }">
          <td-button
            v-if="[0].includes(+row.state)"
            icon="click"
            title="生成"
            @click="generate(row)"
          ></td-button>
          <td-button
            v-if="[2, 3].includes(+row.state)"
            icon="assessed-badge"
            title="重新生成"
            @click="generate(row)"
          ></td-button>
          <td-button
            v-if="[2].includes(+row.state)"
            icon="download"
            title="下载"
            @click="download(row)"
          ></td-button>
          <span v-if="[1].includes(+row.state)">--</span>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script>
import TdButton from '@/components/td-button';
import { loadEnergyMonthReportList, makeReport } from '@/api/energyMonthReport';

const api = {
  loadEnergyMonthReportList,
  makeReport
};
const pickerOptions = Object.freeze({
  disabledDate: date => {
    const current = new Date();
    const currentYear = current.getFullYear();
    const targetYear = date.getFullYear();
    return currentYear < targetYear;
  }
});
const defaultYear = `${new Date().getFullYear()}`;
const columns = Object.freeze([
  { label: 'ID', prop: 'id' },
  { label: '年份', prop: 'year' },
  { label: '月份', prop: 'month' },
  { label: '报告名称', prop: 'name' },
  { label: '报告状态', prop: 'state' }
]);
let timer = null;
export default {
  name: 'energy-discount-coefficient',
  components: {
    TdButton
  },
  data() {
    return {
      loading: false,
      lists: [],
      year: defaultYear,
      columns,
      pickerOptions
    };
  },
  computed: {
    themeColor() {
      return this.$store.state.user.theme;
    }
  },
  beforeDestroy () {
    timer && clearTimeout(timer);
  },
  mounted() {
    this.query();
  },
  methods: {
    polling() {
      if (timer) clearTimeout(timer);
      // 在文件生成可能出现异步的情况，定时刷新
      timer = setTimeout(() => {
        this.query();
      }, 10000);
    },
    reload() {
      this.query();
    },
    query() {
      if (!this.year) return;
      this.loading = true;
      api
        .loadEnergyMonthReportList(this.year)
        .then(res => {
          const { data } = res;
          // 计算当前月份
          this.lists = new Array(12).fill({}).map((_, i) => {
            const month = (i + 1).toString().padStart(2, '0');
            const target = data.find(item => +item.month === +month);
            const state = +(target && target.state) || 0;
            const o = {
              id: i + 1,
              year: this.year,
              month,
              name: (target && target.fileName && target.name) || '-',
              state,
              fileName: (target && target.fileName) || ''
            };
            return o;
          });
        })
        .finally(() => {
          this.loading = false;
          this.polling();
        });
    },
    generate(row) {
      const currentDate = new Date();
      const currentYear = currentDate.getFullYear();
      const currentMonth = currentDate.getMonth() + 1;
      if (+this.year === currentYear && +row.month > currentMonth) {
        this.$message.info('不能生成未来月份的报表!');
        return;
      }
      this.loading = true;
      api
        .makeReport(`${row.year}-${row.month}`)
        .then(({ data, code }) => {
          if (+code !== 200) return;
          this.$message.success(data);
        })
        .catch(err => {
          console.error(err);
        })
        .finally(() => {
          this.query();
          this.loading = false;
        });
    },
    download(row) {
      const state = +(row && row.state) || 0;
      if (state === 1) {
        this.$message.info('正在生成中，请稍后');
        return;
      } else if (state === 3) {
        this.$message.info('生成失败,请重新生成');
        return;
      }
      const fileName = row.fileName;
      console.log(fileName);
      const a = document.createElement('a');
      a.href = fileName;
      a.download = 'download';
      // 绑定点击时间
      // document.body.appendChild(a);
      a.click();
      // 然后移除
      // document.body.removeChild(a);
    }
  }
};
</script>

<style scoped>
a {
  color: var(--theme-color);
}
</style>
